﻿#include "dxstdafx.h"
#include "TerrainIDInfoIO.h"
#include "Data/DataMgr.h"
#include "Data/ScriptData/ScriptDataMgr.h"
#include "Data/ScriptData/TerrainType/TerrainTypeInfo.h"

// (_stTerrainIDInfo*)(m_list_OperatorPtr.back())->P = (*T)(vp)  普通赋值操作
#define NORMAL_ASSIGN(P, T)\
[this](const void* vp){ CHECK_RETURN(vp);\
		_stTerrainIDInfo* cp = static_cast<_stTerrainIDInfo*>(m_list_OperatorPtr.back());\
		CHECK_RETURN(cp);\
		const T* tp = static_cast<const T*>(vp);\
		CHECK_RETURN(tp);\
		cp->P =  *tp; }\

#define UNIQUE_ASSIGN()\
[this](const void* vp){ CHECK_RETURN(vp);\
		_stTerrainIDInfo* cp = static_cast<_stTerrainIDInfo*>(m_list_OperatorPtr.back());\
		CHECK_RETURN(cp);\
		const std::wstring* tp = static_cast<const std::wstring*>(vp);\
		CHECK_RETURN(tp);\
		cp->pTerrainTypeInfo = CDataMgr::Singleton().GetScriptDataMgrCPtr()->GetTerrainTypeInfoCPtr()->GetInfoCPtr(*tp); }\


CTerrainIDInfoReaderHandle::CTerrainIDInfoReaderHandle(std::unordered_map<BYTE, _stTerrainIDInfo>* map)
	: BaseReaderHandler(map)
{
	m_map_OperatorFunction = {
		{ L"color", NORMAL_ASSIGN(nColor, int) },
		{ L"priority", NORMAL_ASSIGN(nPriority, int) },
		{ L"terrain_name", UNIQUE_ASSIGN() },
	};
}

bool CTerrainIDInfoReaderHandle::HandleInt(const std::wstring& key, int i)
{
	return OperatorFunction(key, &i);
}

bool CTerrainIDInfoReaderHandle::HandleString(const std::wstring& key, const std::wstring& str)
{
	return OperatorFunction(key, &str);
}

bool CTerrainIDInfoReaderHandle::HandleStartObj(const std::wstring& key)
{
	if (!key.empty())
	{
		m_TerrainIDInfo.clear();
		m_list_OperatorPtr.push_back(&m_TerrainIDInfo);
	}
	return true;
}
bool CTerrainIDInfoReaderHandle::HandleEndObj()
{
	if (m_list_OperatorPtr.empty())
	{
		return true;
	}
	// 非空 需要操作 m_Container
	// 因为KEY要在HandleInt()中才能取到 所以不能在HandleStartObj()中就赋值
	_stTerrainIDInfo* pstTerrainIDInfo = static_cast<_stTerrainIDInfo*>(m_list_OperatorPtr.back());
	CHECK_RE_FALSE(pstTerrainIDInfo);
	CHECK_RE_FALSE(m_Container);
	auto iterInsert = m_Container->insert(std::make_pair(pstTerrainIDInfo->nColor, *pstTerrainIDInfo));
	if (!iterInsert.second)
	{
		CString strError;
		strError.Format(L"'%s' is repeat!", pstTerrainIDInfo->nColor);
		CommonFunc::ErrorMessageBox(strError);
		return false;
	}
	else
	{
		// 成功 则pop_back m_list_OperatorPtr
		m_list_OperatorPtr.pop_back();
	}
	return true;
}